<template>
  <view class="page">
    <Header> </Header>
    <view class="main_container">
      <view class="main_content">
        <Breadcrumb :text="'个人评测-团灭音标'"> </Breadcrumb>
        <RouterTabs :list="routerList" :current="3"> </RouterTabs>
        <view class="content">
          <view class="title">
            {{ chapterName }}
          </view>
          <view class="letter_container">
            <view class="box">
              <view class="box_letter">
                {{ currentWord.word }}
              </view>
              <view class="box_info">
                {{ currentWord.wordSoundmark }}
                {{ currentWord.wordParaphrase }}
              </view>
            </view>
            <view class="noop" v-if="!isRecord"></view>
            <view class="record" v-else-if="!isSuspend">
              <view class="record_time">
                正在录音{{ minuteNumber }}:{{ secondNumber }}
              </view>
              <RecordShape></RecordShape>
            </view>
            <view class="load" v-else-if="isSuspend && !isHandle">
              <u-loading mode="flower" size="96"></u-loading>
            </view>
            <view class="result" v-else-if="isSuspend && isHandle">
              <view class="result_content">
                <text class="result_content_text">
                  {{ score }}
                </text>
                <text class="result_content_text"> 分 </text>
                <view class="result_info active" v-if="isPass">
                  <text>过关</text>
                </view>
                <view class="result_info" v-else>
                  <text>未过关</text>
                </view>
              </view>
              <view class="phoneme">
                <view class="phoneme_title">
                  <text>标准发音</text>
                  <text>音素匹配</text>
                </view>
                <view class="phoneme_container">
                  <view
                    class="phoneme_content"
                    v-for="(item, index) in syllArray"
                    :key="index"
                  >
                    <text>{{ item.content }}</text>
                    <text
                      class="error"
                      :class="{
                        correct: item.score >= 60,
                      }"
                      >{{ item.score }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
            <view class="icon">
              <view class="icon_content">
                <view class="icon_iamge" @click="play()">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/sound.png"
                    mode="widthFix"
                    style="width: 74rpx"
                  ></image>
                </view>
                <view class="icon_text"> 听声音 </view>
              </view>
              <view class="icon_content active" v-if="!isRecord" @click="record()">
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/sound.png"
                    mode="widthFix"
                    style="width: 52rpx"
                  ></image>
                </view>
                <view class="icon_text"> 开始录音 </view>
              </view>
              <view
                class="icon_content"
                v-else-if="!isSuspend"
                @click="endRecord()"
              >
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/sound.png"
                    mode="widthFix"
                    style="width: 56rpx"
                  ></image>
                </view>
                <view class="icon_text"> 结束录音 </view>
              </view>
              <view class="icon_content" v-else-if="isSuspend && !isHandle">
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/wait.png"
                    mode="widthFix"
                    style="width: 63rpx"
                  ></image>
                </view>
                <view class="icon_text"> 处理中 </view>
              </view>
              <view
                class="icon_content"
                v-else-if="isSuspend && isHandle"
                @click="playVoice()"
              >
                <view class="icon_iamge">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/play.png"
                    mode="widthFix"
                    style="width: 43rpx"
                  ></image>
                </view>
                <view class="icon_text"> 我的录音 </view>
              </view>
            </view>
          </view>
          <view class="button">
            <view class="button_container">
              <view
                class="button_content"
                @click="practiceAgain()"
                v-if="showAnswer"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/ace_button1.png"
                  mode="widthFix"
                  style="width: 180rpx"
                ></image>
              </view>
            </view>
            <view class="button_container">
              <view
                class="button_content active"
                @click="nextQuestion()"
                v-if="isPass && showAnswer"
              >
                <image
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/ace_button2.png"
                  mode="widthFix"
                  style="width: 140rpx"
                ></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>

<script>
import {
  getPhoneticWordsDetail,
  saveAcedChapterProgress,
} from "@/api/spelling";
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
import dictList from "@/libs/PronunciationDict";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
export default {
  components: {},
  data() {
    return {
      routerList: [
        {
          name: "练习字母",
          url: "pages/spelling/letter",
        },
        {
          name: "浅学音标",
          url: "pages/spelling/soundmarkShallow",
        },
        {
          name: "拼读训练",
          url: "pages/spelling/spellingTraining",
        },
        {
          name: "团灭音标",
          url: "pages/spelling/soundmarkAce",
        },
        {
          name: "暴击词汇",
          url: "pages/spelling/vocabulary",
        },
      ],
      id: "",
      chapterName: "",
      wordList: [],
      currentWord: {},
      currentIndex: 0,
      syllArray: [],
      timerId: null,
      second: 0,
      minute: 0,
      secondNumber: "00",
      minuteNumber: "00",
      isRecord: false,
      isSuspend: false,
      isHandle: false,
      isRejected: "false",
      score: 0,
      isPass: false,
      showAnswer: false,
      isShowPopup: false,
      isShowGold: false,
      goldNum: 0,
      isCanClick: true,
      showTips: false,
      tipsContent: "请不要乱读哦~",
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
    };
  },
  onLoad(option) {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
    this.id = option.id;
    this.init();
  },
  methods: {
    init() {
      getPhoneticWordsDetail(this.id).then((res) => {
        this.chapterName = res.data.chapter.chapterName;
        this.wordList = res.data.list;
        this.initWord();
      });
    },
    initWord() {
      this.currentWord = this.wordList[this.currentIndex];
    },
    initData() {
      this.isRecord = false;
      this.isSuspend = false;
      this.isHandle = false;
      this.showAnswer = false;
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.time();
      this.isRecord = true;
    },
    endRecord() {
      this.isSuspend = true;
      recorderManager.stop();
      clearInterval(this.timerId);
      this.second = 0;
      this.minute = 0;
    },
    playVoice() {
      if (!englishAudioContext.paused) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, { wordText: this.currentWord.word }).then(
        (res) => {
          let xml = res.data;
          let grade = parser.parse(xml, {
            attributeNamePrefix: "",
            ignoreAttributes: false,
          });
          if (grade) {
            let read_chapter =
              grade.xml_result.read_sentence.rec_paper.read_chapter;
            this.getSyllData(read_chapter);
            this.isRejected = read_chapter.is_rejected;
            if (this.isRejected === "true") {
              this.showTips = true;
              setTimeout(() => {
                this.showTips = false;
              }, 2000);
            }
            this.score = Number(read_chapter.total_score).toFixed(2);
            this.isPass = this.score >= 60 ? true : false;
            this.isHandle = true;
            this.showAnswer = true;
          }
        }
      );
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.currentWord.wordAudio;
      englishAudioContext.play();
    },
    practiceAgain() {
      this.initData();
    },
    nextQuestion() {
      if (this.currentIndex === this.wordList.length - 1) {
        this.saveProgress();
        return;
      }
      this.initData();
      this.currentIndex++;
      this.initWord();
    },
    saveProgress() {
      let params = {
        chapterId: this.id,
      };
      saveAcedChapterProgress(params).then((res) => {
        this.isShowGold = res.data.hasGold;
        if (this.isShowGold) this.goldNum = res.data.goldNum;
        this.isShowPopup = true;
      });
    },
    getSyllData(result) {
      let syllArray = [];
      let sentence = result.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.content === "fil" || item.content === "sil") return;
          let anSyllArray = [];
          if (!Array.isArray(item.syll)) {
            anSyllArray.push(item.syll);
          } else {
            anSyllArray = item.syll;
          }
          anSyllArray.forEach((item) => {
            let syll_score = Number(item.syll_score).toFixed(2);
            const nonStandard = item.content;
            const splitResult = nonStandard.split(" "); // 分割成 ["eh", "m"]
            const standardResult = splitResult
              .map((phoneme) => {
                const found = dictList.find(
                  (item) => item.nonstandard === phoneme
                );

                return found ? found.standard : phoneme; // 如果找到映射则替换，否则保持原样
              })
              .join(" ");
            let syll_content = standardResult;
            syllArray.push({
              content: syll_content,
              score: syll_score,
            });
          });
        });
      });
      this.syllArray = syllArray;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./soundmarkAceWord";
</style>
